Skip to content

feat(schema): unify pydantic model, mirror permissions in ActionSchema, add side_effect - #293

Merged
traoreera merged 1 commit into
mainfrom
feat/schema-permissions-side-effect
Oct 10, 2026
Merged

traoreera merged 1 commit into
mainfrom
feat/schema-permissions-side-effect

Conversation

@traoreera

@traoreera traoreera commented Oct 10, 2026 •

Copy link
Copy Markdown
Owner

Summary

  • @schema now builds the pydantic Model once and passes it directly to validate_payload(schema=Model, ...) instead of each rebuilding their own from the same input dict. That same Model.model_json_schema() is stored as input_json_schema/output_json_schema on ActionSchema — a real JSON Schema (nested fields, defaults, constraints), not just the existing flat {field: type_name} dict (kept as-is, still what BreakingChangeDetector compares).
  • permissions/permission_groups were only readable via a live LifecycleManager per plugin instance. Mirrored them onto ActionSchema, and widened _register_schemas() to register an entry for every @action (not only those with @schema also stacked) — otherwise an action with only permissions and no schema silently never reached schema_registry at all. External tooling can now read schema + permissions for the whole system from schema_registry alone.
  • permissions answers "who can call this", not "how consequential is it once authorized". @action(side_effect="read"|"write"|"outbound") declares that as an orthogonal, purely informational axis (also mirrored on ActionSchema) — the kernel enforces nothing on it, it's for an external consumer (e.g. a bridge exposing actions as LLM tools) to decide whether an action needs approval first. Invalid values raise ValueError at decoration time.

Test plan

  • poetry run pytest tests/unit tests/integration -q — 1415 passed, 1 pre-existing unrelated skip
  • poetry run mkdocs build --strict — clean (pre-existing unrelated warnings only)
  • make lint-check — passed
  • pre-commit hooks (trim whitespace, bandit, test & coverage) passed on the commit

Summary by Sourcery

Unify action schema generation and expand the action registry with authorization and side-effect metadata for external consumers.

New Features:

  • Add declarative action side-effect classification with validation and expose it alongside permissions.
  • Expose complete JSON Schema metadata and action authorization metadata through the central schema registry for every action.

Bug Fixes:

  • Ensure actions without an associated schema are registered so their permissions and metadata are not omitted from the registry.

Enhancements:

  • Reuse the same Pydantic models for schema validation and JSON Schema generation while preserving existing flat schema metadata for breaking-change detection.
  • Mirror permissions, permission groups, and side-effect declarations on ActionSchema for external consumers.

Documentation:

  • Document permission groups, side-effect classification, complete JSON Schema metadata, and registry-based action metadata discovery.

Tests:

  • Add coverage for side-effect validation, generated JSON Schema, unified validation, and registry entries for schema-less actions.

…a, add side_effect

Three related gaps closed:

1. @Schema built its own pydantic Model via create_model(), then separately
   handed the raw input dict to validate_payload() which built ANOTHER model
   from scratch. Now @Schema builds the Model once and passes it directly to
   validate_payload(schema=Model, ...). That same Model's model_json_schema()
   is stored as input_json_schema/output_json_schema on ActionSchema — a real
   JSON Schema (nested fields, defaults, constraints), not just the existing
   flat {field: type_name} dict (kept as-is, still what BreakingChangeDetector
   compares).

2. permissions/permission_groups lived only on the function
   (_xcore_action_permissions/_xcore_action_permission_groups), readable only
   via a live LifecycleManager.get_action_permissions()/
   get_action_permission_groups() per plugin instance. Mirrored them onto
   ActionSchema too, and widened _register_schemas() to register an entry for
   every @action (not only those with @Schema also stacked) — otherwise an
   action with only permissions and no schema silently never reached
   schema_registry at all. External tooling can now read schema AND
   permissions for the whole system from schema_registry alone.

3. permissions answers "who can call this", not "how consequential is it
   once authorized" — a legitimate caller can still trigger something
   irreversible. @action(side_effect="read"|"write"|"outbound") declares that
   as an orthogonal, purely informational axis (also mirrored on
   ActionSchema): the kernel enforces nothing on it itself, it's for an
   external consumer (e.g. a bridge exposing actions as LLM tools) to decide
   whether an action can be a direct tool or needs approval first. Invalid
   values raise ValueError at decoration time.
@sourcery-ai

sourcery-ai Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Reviewer's Guide

The PR unifies Pydantic model construction for validation and rich JSON Schema generation, expands ActionSchema and registration into a complete metadata catalog for all actions, adds declarative side-effect classification, and documents the resulting authorization and external-tooling semantics.

Sequence diagram for action metadata registration

sequenceDiagram
    participant Plugin as PluginMixin
    participant Method as DecoratedAction
    participant Registry as SchemaRegistry
    participant Catalog as ExternalConsumer

    Plugin->>Plugin: _register_schemas(plugin_name)
    Plugin->>Method: Read _xcore_action and metadata
    Method-->>Plugin: action, schema, permissions, side_effect
    Plugin->>Registry: register(ActionSchema)
    Registry-->>Catalog: Complete action catalog
    Catalog->>Registry: Read schema and authorization metadata
Loading

Sequence diagram for unified schema model validation

sequenceDiagram
    participant Decorator as schema
    participant Model as PydanticModel
    participant Validator as validate_payload
    participant Action as ActionHandler
    participant Consumer as SchemaConsumer

    Decorator->>Model: create_model(input)
    Decorator->>Validator: validate_payload(schema=Model)
    Decorator->>Model: model_json_schema()
    Model-->>Decorator: input_json_schema
    Decorator->>Action: Store schema metadata
    Consumer->>Action: Read input_json_schema
Loading

Flow diagram for authorization and side-effect classification

flowchart LR
    Action["@action metadata"] --> Auth["Authorization requirements"]
    Auth --> Permissions["permissions: AND"]
    Auth --> Groups["permission_groups: OR of AND"]
    Permissions --> Authorized["Authorized call"]
    Groups --> Authorized
    Authorized --> Risk["side_effect classification"]
    Risk --> Consumer["External consumer decides approval"]
Loading

File-Level Changes

Change Details Files
Build and retain unified Pydantic models for validation and full JSON Schema metadata.
  • Construct input and output models once in @Schema.
  • Pass the input model to validate_payload.
  • Store complete JSON Schemas alongside the existing flat type maps.
xcore/sdk/decorators.py
doc/sdk/api/decorators.md
tests/unit/plugins/test_decorators.py
Make the schema registry a complete action catalog with authorization and risk metadata.
  • Register every @action, including actions without @Schema.
  • Mirror permissions, permission groups, side effect, and JSON Schema fields onto ActionSchema.
  • Preserve empty/default metadata for undeclared schemas and permissions.
xcore/sdk/mixin/ipc.py
xcore/kernel/schema/registry.py
doc/sdk/api/decorators.md
doc/sdk/api/auth.md
tests/unit/plugins/test_decorators.py
Add declarative side-effect classification to actions.
  • Support read, write, and outbound values on @action.
  • Reject invalid values at decoration time.
  • Keep side_effect informational and independent from authorization enforcement.
xcore/sdk/decorators.py
xcore/kernel/schema/registry.py
doc/sdk/api/decorators.md
doc/sdk/api/auth.md
tests/unit/plugins/test_decorators.py
Document expanded action authorization semantics and registry usage.
  • Document permission_groups as OR-of-AND requirements and its combination with permissions.
  • Clarify fail-closed behavior for declared requirements without a principal.
  • Explain registry access for external tooling without live plugin instances.
doc/sdk/api/auth.md
doc/sdk/api/decorators.md

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

@github-actions github-actions Bot added documentation Improvements or additions to documentation core tests labels Oct 10, 2026
@github-actions

Copy link
Copy Markdown
Contributor

@sourcery-ai sourcery-ai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've found 3 issues

Prompt for AI Agents
Please address the comments from this code review:

## Individual Comments

### Comment 1
<location path="xcore/sdk/decorators.py" line_range="131-133" />
<code_context>
             "deprecated_fields": deprecated_fields or {},
             "breaking_since": breaking_since,
             "description": description,
+            "input_json_schema": InputModel.model_json_schema() if InputModel else {},
+            "output_json_schema": (
+                OutputModel.model_json_schema() if OutputModel else {}
+            ),
         }
</code_context>
<issue_to_address>
**Actions fail during import**

When an input or output field has a Pydantic-supported type without a JSON Schema representation, such as `Callable`, `model_json_schema()` raises while the decorator builds schema metadata, so the action fails to load even when validation is disabled or the output model is metadata-only.

Make JSON Schema generation non-fatal for types without a JSON Schema representation.
</issue_to_address>

### Comment 2
<location path="xcore/kernel/schema/registry.py" line_range="43-44" />
<code_context>
+    # BreakingChangeDetector (comparaison type-par-type) ; ces deux champs sont
+    # pour les consommateurs externes (génération de tools LLM, OpenAPI, etc.)
+    # qui ont besoin de la forme complète, pas juste du nom du type.
+    input_json_schema: dict[str, Any] = field(default_factory=dict)
+    output_json_schema: dict[str, Any] = field(default_factory=dict)
+    # Miroir de fn._xcore_action_permissions / _xcore_action_permission_groups
+    # (@action(permissions=..., permission_groups=...), voir sdk/decorators.py).
</code_context>
<issue_to_address>
**Older readers discard schema snapshots**

When an older CLI or runtime loads a snapshot written by this version, `ActionSchema.to_dict()` persists the added fields, but older strict `ActionSchema` constructors reject them and `SchemaRegistry.load()` skips the entries. Rollbacks then lose the schemas used for breaking-change comparisons.

Make loading tolerate unknown fields or version and migrate the snapshot format.
</issue_to_address>

### Comment 3
<location path="xcore/sdk/decorators.py" line_range="193-197" />
<code_context>
         async def create_user(self, payload: dict) -> dict:
             ...
     """
+    if side_effect is not None and side_effect not in _VALID_SIDE_EFFECTS:
+        raise ValueError(
+            f"side_effect invalide : {side_effect!r} — attendu l'un de "
+            f"{sorted(_VALID_SIDE_EFFECTS)} ou None"
+        )

     def decorator(fn: Callable) -> Callable:
</code_context>
<issue_to_address>
**Invalid values raise wrong exception**

When a caller passes an unhashable invalid `side_effect`, such as a list or dict, the membership check against `_VALID_SIDE_EFFECTS` hashes the value and raises `TypeError` instead of the documented `ValueError` at decoration time.

Validate the value without hashing unhashable inputs, and raise `ValueError` for invalid values.
</issue_to_address>

Sourcery assessment

Approval pending. 2 findings to address first.

Blocking findings: xcore/sdk/decorators.py:133, xcore/kernel/schema/registry.py:44


Sourcery is free for open source - if you like our reviews please consider sharing them ✨

Comment thread xcore/sdk/decorators.py
Comment on lines +131 to +133
"input_json_schema": InputModel.model_json_schema() if InputModel else {},
"output_json_schema": (
OutputModel.model_json_schema() if OutputModel else {}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟠 High · Actions fail during import

When an input or output field has a Pydantic-supported type without a JSON Schema representation, such as Callable, model_json_schema() raises while the decorator builds schema metadata, so the action fails to load even when validation is disabled or the output model is metadata-only.

Make JSON Schema generation non-fatal for types without a JSON Schema representation.

Prompt for AI agents
In `xcore/sdk/decorators.py` at lines 131-133:

**Actions fail during import**

When an input or output field has a Pydantic-supported type without a JSON Schema representation, such as `Callable`, `model_json_schema()` raises while the decorator builds schema metadata, so the action fails to load even when validation is disabled or the output model is metadata-only.

Make JSON Schema generation non-fatal for types without a JSON Schema representation.

Comment on lines +43 to +44
input_json_schema: dict[str, Any] = field(default_factory=dict)
output_json_schema: dict[str, Any] = field(default_factory=dict)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 Medium · Older readers discard schema snapshots

When an older CLI or runtime loads a snapshot written by this version, ActionSchema.to_dict() persists the added fields, but older strict ActionSchema constructors reject them and SchemaRegistry.load() skips the entries. Rollbacks then lose the schemas used for breaking-change comparisons.

Make loading tolerate unknown fields or version and migrate the snapshot format.

Prompt for AI agents
In `xcore/kernel/schema/registry.py` at lines 43-44:

**Older readers discard schema snapshots**

When an older CLI or runtime loads a snapshot written by this version, `ActionSchema.to_dict()` persists the added fields, but older strict `ActionSchema` constructors reject them and `SchemaRegistry.load()` skips the entries. Rollbacks then lose the schemas used for breaking-change comparisons.

Make loading tolerate unknown fields or version and migrate the snapshot format.

Comment thread xcore/sdk/decorators.py
Comment on lines +193 to +197
if side_effect is not None and side_effect not in _VALID_SIDE_EFFECTS:
raise ValueError(
f"side_effect invalide : {side_effect!r} — attendu l'un de "
f"{sorted(_VALID_SIDE_EFFECTS)} ou None"
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ Low · Invalid values raise wrong exception

When a caller passes an unhashable invalid side_effect, such as a list or dict, the membership check against _VALID_SIDE_EFFECTS hashes the value and raises TypeError instead of the documented ValueError at decoration time.

Validate the value without hashing unhashable inputs, and raise ValueError for invalid values.

Prompt for AI agents
In `xcore/sdk/decorators.py` at lines 193-197:

**Invalid values raise wrong exception**

When a caller passes an unhashable invalid `side_effect`, such as a list or dict, the membership check against `_VALID_SIDE_EFFECTS` hashes the value and raises `TypeError` instead of the documented `ValueError` at decoration time.

Validate the value without hashing unhashable inputs, and raise `ValueError` for invalid values.

@traoreera
traoreera merged commit 5be597c into main Oct 10, 2026
25 checks passed
@traoreera traoreera mentioned this pull request Oct 12, 2026
4 tasks done
traoreera added a commit that referenced this pull request Oct 12, 2026
## Summary
- CHANGELOG entry for `permission_groups`, `side_effect`, and the
`ActionSchema`/registry work from #292 and #293.
- Version bump to 2.9.0: `pyproject.toml`, `xcore/__version__.py` (also
fixes `__version_info__`, which had drifted to `(2, 7, 1)` since the
2.8.1 bump — left stale by that release), `CLAUDE.md`.
- `CLAUDE.md`'s HTTP call-flow diagram and
`doc/advanced/middleware.md`'s Action Permissions section now mention
`permission_groups`, not just `permissions`.

## Test plan
- [x] `poetry run pytest tests/unit tests/integration -q` — 1415 passed,
1 pre-existing unrelated skip
- [x] `poetry run mkdocs build --strict` — clean (pre-existing unrelated
warnings only)
- [x] version consistent across all three files
- [x] pre-commit hooks passed on the commit

## Summary by Sourcery

Release version 2.9.0 with updated version metadata, changelog coverage,
and documentation for the new action authorization and schema
capabilities.

Bug Fixes:
- Correct the stale `__version_info__` value so it matches the released
version.

Enhancements:
- Document action permission groups and their authorization behavior.
- Document the updated HTTP middleware flow and the distinction between
action permissions and plugin ACL permissions.

Build:
- Bump the project version to 2.9.0 across package metadata and runtime
version information.

Documentation:
- Add the 2.9.0 changelog covering permission groups, side-effect
metadata, enriched action schemas, and schema registration changes.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

core documentation Improvements or additions to documentation tests

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant